//
//  GenresDataSource.m
//  MantuPlay
//
//  Created by Markus Sintonen on 14.8.2009.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "GenresDataSource.h"
#import "TrackDatabase.h"
#import "Genre.h"
#import "ArtistsDataSource.h"

#define ROW_HEIGHT 46.0
#define OBJECTCOUNTLABEL_TAG 4

@implementation GenresDataSource

- (id)init {
	if ((self = [super init])) {
		
	}
	return self;
}

-(NSArray*)databaseObjectArray {
	return genres;
}

- (NSString*)name {
	return @"Genres";
}

- (NSString*)navigationBarName {
	return @"Genres";
}

-(CGFloat)rowHeight {
	return ROW_HEIGHT;
}

-(BOOL)showSectioned {
	return YES;
}

-(BOOL)extraRowAtTop {
	return NO;
}
-(BOOL)extraRowAtBottom {
	return ([genres count] > 5);
}

-(void)loadData {
	if(!genres) {
		NSArray *tempGenres = [[TrackDatabase sharedTrackDatabase] allGenres];
		genres = [[NSArray alloc] initWithArray:tempGenres];
	}
}
-(void)unloadData {
	[genres release];
	genres = nil;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForObject:(id)obj atIndexPath:(NSIndexPath*)indexPath {
	static NSString *CellIdentifier = @"GenreCell";
	
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithFrame:CGRectMake(0,0,0,0) reuseIdentifier:CellIdentifier] autorelease];
	}
	
	Genre *genre = (Genre*)obj;
	cell.text = genre.title;
	
	return cell;	
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForExtraRowAtBottomIndexPath:(NSIndexPath*)indexPath {
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ObjectCountCell"];
	UILabel *objectCountLabel;
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithFrame:CGRectMake(0,0,0,0) reuseIdentifier:@"ObjectCountCell"] autorelease];
		
		objectCountLabel = [[[UILabel alloc] initWithFrame:CGRectMake(1.0, 1.0, 320.0-1.0, ROW_HEIGHT-2.0)] autorelease];
		objectCountLabel.tag = OBJECTCOUNTLABEL_TAG;
		objectCountLabel.textColor = [UIColor grayColor];
		objectCountLabel.textAlignment = UITextAlignmentCenter;
		[cell.contentView addSubview:objectCountLabel];
	} else {
		objectCountLabel = (UILabel *)[cell.contentView viewWithTag:OBJECTCOUNTLABEL_TAG];
	}
	objectCountLabel.text = [NSString stringWithFormat:@"%d genres", [genres count]];
	
	return cell;
}

-(id<DatabaseObjectDataSource>)tableView:(UITableView *)tableView dataSourceForSelectedObject:(id)obj atIndexPath:(NSIndexPath *)indexPath {
	Genre *genre = (Genre*)obj;
	
	ArtistsDataSource<DatabaseObjectDataSource> *artistDataSource;
	artistDataSource = [[ArtistsDataSource alloc] initWithArtistsFromGenre:genre.title];
	
	artistDataSource.artistsFromGenre = genre.title;
	artistDataSource.navigationBarTitle = genre.title;
	
	return [artistDataSource autorelease];
}

- (void)dealloc {
	[genres release];
	[super dealloc];
}
@end
